package cn.wolfcode.mq;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 延迟消费者：消费延迟消息，判断订单的支付状态，并做相关的逻辑业务操作
 *
 */
@Component
@RocketMQMessageListener(consumerGroup = "delayconsumer",
                        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
                        messageModel = MessageModel.CLUSTERING  //注意如果有多个服务，则消费者们需要做成集群模式（一个消息只能被消费一次）
)
public class OrderReslutSuccess_Timeout_Listener implements RocketMQListener<OrderMQResult> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        //1、判断当前订单的支付状态，如果未支付
        OrderInfo orderInfo=orderInfoService.getOrderInfo(orderMQResult.getOrderNo());
        if(orderInfo.getStatus().equals(OrderInfo.STATUS_ARREARAGE)){
            //2、回补真实库存+1（先回补真实库存）
            seckillProductService.incrStackCount(orderMQResult.getSeckillId());
            //3、回补该秒杀商品的预库存
            seckillProductService.initPreCountInRedis(orderInfo.getSeckillTime(),orderInfo.getSeckillId());
            //4、修改本地标识
            //消息为orderMQResult，因为里面封装了相关消息
            rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMQResult);
            //5、修改订单状态为超时取消
            orderInfoService.updateStatus(orderMQResult.getOrderNo());
        }
    }
}
